from flask import request, jsonify
from flask.views import MethodView
from ..auth import auth_required
from ..forms import FileUploadForm
from app.helpers import oss_bucket
from datetime import datetime
from uuid import uuid4
from app.models.attachment import Attachment
from app.extensions import db
from flask_login import current_user


class AttachmentAPI(MethodView):
    decorators = [auth_required]

    def post(self):
        fileForm = FileUploadForm()
        if fileForm.validate_on_submit():
            file = request.files.get('upload')
            extension = file.filename.split('.')[1].lower()
            filename = '/'.join([datetime.now().strftime('%Y-%m-%d'), '{}.{}'.format(uuid4(), extension)])
            oss_bucket.put_object(filename, file.read())
            model = Attachment(url=filename)
            db.session.add(model)
            db.session.commit()
            return jsonify(success=True, id=model.id, url=model.to_dict())

        return jsonify(success=False, message=fileForm.errors['upload'])

    def delete(self, id):
        model = Attachment.query.get_or_404(id)
        if model.article is None or model.article.user != current_user:
            return jsonify(success=False, message="你没有权限删除不是自已的附件")

        db.session.delete(model)
        db.session.commit()
        
        return jsonify(success=True, message="删除成功")
